package org.applet.game.framework.util;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;

import org.applet.game.framework.core.common.Picture;

public class ImageLoader {

	Map<String, Image> imageCache = new HashMap<String, Image>();
	
	public static BufferedImage loadImage(String filePath)
	{
		if(filePath == null)
			return null;
		try {
			return ImageIO.read(new File(filePath));
		} catch (IOException e) {
			throw new RuntimeException(e+" : "+filePath);
		}
	}
	
	public static BufferedImage loadImage(File file)
	{
		try {
			return ImageIO.read(file);
		} catch (IOException e) {
			throw new RuntimeException(e+" : "+file);
		}
	}
	
	public static Picture loadPicture(String filePath, int imageX, int imageY, int imageWidth, int imageHeight)
	{
		return new Picture(loadImage(filePath), imageX, imageY, imageWidth, imageHeight);
	}
	
	public static Picture loadPicture(String filePath)
	{
		BufferedImage image = loadImage(filePath);
		return new Picture(image, 0, 0, image.getWidth(), image.getHeight());
	}
	
	public static void saveImageTo(BufferedImage image, String file, String fix)
	{
		try {
			ImageIO.write(image, fix, new FileOutputStream(file));
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}
	
	public void disposeImage(Image image)
	{
		imageCache.remove(image);
	}
}
